package org.jeecg.modules.hems.regionalmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.hems.regionalmanagement.entity.BsMapArea;
import org.jeecg.modules.hems.regionalmanagement.mapper.BsMapAreaMapper;
import org.jeecg.modules.hems.regionalmanagement.service.IBsMapAreaService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: 区域管理
 * @Author: jeecg-boot
 * @Date:   2022-06-27
 * @Version: V1.0
 */
@Service
public class BsMapAreaServiceImpl extends ServiceImpl<BsMapAreaMapper, BsMapArea> implements IBsMapAreaService {
    @Override
    public void addBsMapArea(BsMapArea bsMapArea) {
        if(oConvertUtils.isEmpty(bsMapArea.getParentId())){
            bsMapArea.setParentId(IBsMapAreaService.ROOT_PID_VALUE);
        }else{
            //如果当前节点父ID不为空 则设置父节点的hasChildren 为1
            BsMapArea parent = baseMapper.selectById(bsMapArea.getParentId());
            if(parent!=null && !"1".equals(parent.getHasChild())){
                parent.setHasChild("1");
                baseMapper.updateById(parent);
            }
        }
        baseMapper.insert(bsMapArea);
    }

    @Override
    public void updateBsMapArea(BsMapArea bsMapArea) {
        BsMapArea entity = this.getById(bsMapArea.getId());
        if(entity==null) {
            throw new JeecgBootException("未找到对应实体");
        }
        String old_pid = entity.getParentId();
        String new_pid = bsMapArea.getParentId();
        if(!old_pid.equals(new_pid)) {
            updateOldParentNode(old_pid);
            if(oConvertUtils.isEmpty(new_pid)){
                bsMapArea.setParentId(IBsMapAreaService.ROOT_PID_VALUE);
            }
            if(!IBsMapAreaService.ROOT_PID_VALUE.equals(bsMapArea.getParentId())) {
                baseMapper.updateTreeNodeStatus(bsMapArea.getParentId(), IBsMapAreaService.HASCHILD);
            }
        }
        baseMapper.updateById(bsMapArea);
    }

    @Override
    public void deleteBsMapArea(String id) throws JeecgBootException {
        BsMapArea bsMapArea = this.getById(id);
        if(bsMapArea==null) {
            throw new JeecgBootException("未找到对应实体");
        }
        updateOldParentNode(bsMapArea.getParentId());
        baseMapper.deleteById(id);
    }



    /**
     * 根据所传pid查询旧的父级节点的子节点并修改相应状态值
     * @param pid
     */
    private void updateOldParentNode(String pid) {
        if(!IBsMapAreaService.ROOT_PID_VALUE.equals(pid)) {
            Integer count = baseMapper.selectCount(new QueryWrapper<BsMapArea>().eq("parent_id", pid));
            if(count==null || count<=1) {
                baseMapper.updateTreeNodeStatus(pid, IBsMapAreaService.NOCHILD);
            }
        }
    }
}
